import React,{ useEffect, useState } from 'react';
import { Modal, Form, Input, Row, Col, Checkbox } from 'antd';
import FirstOrgListComponent from './FirstOrgListComponent';
import PermissionComponent from './PermissionComponent';
import { FormInstance } from 'antd/lib/form';
import { RoleListItem } from '../data.d';
import styles from '../index.less';

interface AddRoleFormProps {
  modalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: RoleListItem) => void;
  values: RoleListItem;
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();

const AddRoleForm: React.FC<AddRoleFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;
  
  const [disabled, setDisabled] = useState<boolean>(false);
  const [param, setParam] = useState<number>();
  const [checkedKeysList, setCheckedKeysList] = useState<[]>();
  
  const [form] = Form.useForm();

  useEffect(() => {
    if(modalVisible){
      if(values.code){//编辑
        form.setFieldsValue({
          id: values.id,
          name:values.name,
          topOrgId: values.topOrgId,
          permissionId:values.permissionIds,
          systemDefaultFlag:values.scope=="SYSTEM"?true:false,
          remark: values.remark,
        });
        if(values.scope=="SYSTEM"){//系统角色 只有root用户可以编辑
          setParam(10000);
        }else{
          setParam(values?.topOrgId);
        }
        setCheckedKeysList(values.permissionIds);
        setDisabled(true);
      }else{//新建
        form.resetFields();
        setParam(JSON.parse(localStorage.getItem("user")).topOrgId);
        setCheckedKeysList([]);
        setDisabled(false);
      }
    }
  },[modalVisible]);
  
  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as RoleListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const onSelectChange =(e:Event)=>{
    form.setFieldsValue({systemDefaultFlag:e.target.checked});
  }
  
  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  const renderContent = () => {
    return (
      <>
      <Row>
        <Col span={12}>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="name"
          label="角色名称"
          rules={[
            { required: true, max: 16, whitespace: true }]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>
        <Form.Item name="topOrgId" label="所属机构" rules={[{ required: true }]}>
            <FirstOrgListComponent 
              disabled={disabled} 
              init={true}
              defaultvalue={values?values.topOrgId:null} 
              selectChange={(value) => {
                form.setFieldsValue({topOrgId:value});
                setParam(value);
                if(values.topOrgId === value){
                  setCheckedKeysList(values?.permissionIds);
                }else{
                  setCheckedKeysList([]);
                }
              }}>
            </FirstOrgListComponent>
        </Form.Item>
        <Form.Item
          name="systemDefaultFlag"
          label="系统角色"
          style={{display:JSON.parse(localStorage.getItem("user"))?.orgId === 10000?"flex":"none"}}
        >
          <Checkbox 
            disabled={disabled} 
            defaultChecked={values?.scope=="SYSTEM"?true:false} 
            onChange={onSelectChange}
          ></Checkbox>
        </Form.Item>
        <Form.Item
          name="remark"
          label="角色描述"
        >
          <Input.TextArea
            rows={4}
            style={{resize:"none"}} 
            maxLength={200}
            placeholder="描述最多200个字"
          />
        </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item name="permissionId" label="权限设置" rules={[{ required: true,message:'请设置权限' }]}>
            <div className={styles.treeContent}>
              <PermissionComponent
                edit={true}
                param={param} //编辑用当条数据的topOrgId 新建用当前用户的topOrgId
                disabled={false} 
                checkedKeysList={checkedKeysList} 
                selectChange={(value) => {
                  form.setFieldsValue({permissionId:value});
                }}>
            </PermissionComponent>
            </div>
          </Form.Item>
        </Col>
      </Row>
      </>
    );
  };
  return (
    <Modal 
      destroyOnClose 
      title={values&&values.id?"编辑角色":"添加角色"} 
      visible={modalVisible} 
      {...modalFooter} 
      centered
      width={800}
    >
      <Form 
        {...layout}
        ref={formRef} 
        form={form}
        onFinish={handleFinish}
      >
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default AddRoleForm;
